<?php
class IndexController extends Zend_Controller_Action{
	
	public function init(){
	      
	      $layoutPath = APPLICATION_PATH  . '/templates/front/default';
	      $option = array ('layout' => 'index', 
	                   'layoutPath' => $layoutPath );
	      Zend_Layout::startMvc ( $option );
	      
	}
	public function indexAction(){
		if( isset($_COOKIE['user'])){
			setcookie('user', '', time() - 3600);
			setcookie('pass', '', time() - 3600);
		}
	}
	
	public function loginAction() {
		ob_start();
		if( isset($_COOKIE['user']) and $_COOKIE['pass'] != ""){
			switch ($_COOKIE['user']){
					case "admin": $this->_redirect('/admin/index/index');break;
					case "user": $this->_redirect('/user/index/index');break;
				}
		}else if($this->_request->isPost()){
			
			//1.Goi ket noi voi Zend Db
			$db = Zend_Registry::get('connectDB');
			//$db = Zend_Db::factory($dbOption['adapter'],$dbOption['params']);
			
			//2. Khoi tao Zend Autho
			$auth = Zend_Auth::getInstance ();
			
			//3. Khai bao bang va 2 cot se su dung so sanh trong qua tronh login
			$authAdapter = new Zend_Auth_Adapter_DbTable ( $db );
			$authAdapter->setTableName('users')
					    ->setIdentityColumn('username')
					    ->setCredentialColumn('password');

			//4. Lay gia tri duoc gui qua tu FORM
			$uname = $this->_request->getParam ( 'txtUsername' );
			$paswd = $this->_request->getParam ( 'txtPassword' );
			
			//5. Dua vao so sanh voi du lieu khai bao o muc 3
			$authAdapter->setIdentity ( $uname );
			$authAdapter->setCredential ( md5 ( $paswd ) );
			
			//6. Kiem tra trang thai cua user neu status = 1 moi duoc login
			$select = $authAdapter->getDbSelect();
			$select->where('status = 1');
			
			//7. Lay ket qua truy van
			$result = $auth->authenticate ( $authAdapter );
			$flag = false;
			if($result->isValid()){
				//8. Lay nhung du lieu can thiet trong bang users neu login thanh cong				
				$data = $authAdapter->getResultRowObject (null,array('password'));			
			
				//9. Luu  nhung du lieu cua member vao session
				$auth->getStorage()->write ( $data );
				$flag = true;
				
			}
			if($flag == true){
				
				$infoUser = $auth->getIdentity();
				//10. Luu nhung du lieu cua mamber vao cookie
				if(  $this->_request->getParam('checkBoxGhiNho')){
					setcookie('user', $uname, time() + 3600);
					setcookie('pass', $paswd, time() + 3600);
				}
				switch ($infoUser->decentralize){
					case "admin": $this->_redirect('/admin/index/index');break;
					case "user": $this->_redirect('/user/index/index');break;
				}
				
			}else {
				$this->_redirect('/front/index/errorlogin');
			}
			
		}
	}
	
	public function logoutAction() {
		$auth = Zend_Auth::getInstance(); 
		$auth->clearIdentity();
		
	}
	
	public function errorloginAction(){
		
	} 
}